/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.opencfg.core;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Net Utils
 * 
 * @author opencfg.com
 * @since 0.0.1-SNAPSHOT
 * @version 0.0.1-SNAPSHOT
 * @date 2011-01-16
 */
public class NetUtils {

	/**
	 * 获取本机网卡地址
	 * 
	 * @throws SocketException
	 */
	public static String[] getNetWorkAddress() throws SocketException {
		Enumeration<NetworkInterface> interfaceEnumeration = NetworkInterface
				.getNetworkInterfaces();
		List<String> addrList = new ArrayList<String>();
		if (interfaceEnumeration == null) {
			return null;
		}
		while (interfaceEnumeration.hasMoreElements()) {
			NetworkInterface iface = interfaceEnumeration.nextElement();
			Enumeration<InetAddress> addrEnumeration = iface.getInetAddresses();
			if (addrEnumeration == null) {
				return null;
			}
			while (addrEnumeration.hasMoreElements()) {
				InetAddress address = addrEnumeration.nextElement();
				if (address != null) {
					addrList.add(address.getHostAddress());
				}
			}
		}
		return addrList.toArray(new String[addrList.size()]);
	}
	
	public static String[] getNetworkInterfaceAddr(String name) throws SocketException {
		List<String> addrList = new ArrayList<String>();
		NetworkInterface iface = NetworkInterface.getByName(name);
		Enumeration<InetAddress> addrEnumeration = iface.getInetAddresses();
		if (addrEnumeration == null) {
			return null;
		}
		while (addrEnumeration.hasMoreElements()) {
			InetAddress address = addrEnumeration.nextElement();
			if (address != null) {
				addrList.add(address.getHostAddress());
			}
		}
		return addrList.toArray(new String[addrList.size()]);
	}
	
	public static String getDefaultNetworkAddress() throws SocketException {
		String[] addrs = getNetworkInterfaceAddr("eth0");
		if(addrs != null && addrs.length != 0) {
			return addrs[0];
		} else {
			
		}
		return null;
	}
	
}
